/**
 * 
 */
package internal.standard;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.lightcommons.logger.Log;
import org.lightcommons.logger.LogFactory;
import org.lightcommons.util.PatternMap;
import org.lightmtv.LightMtvException;
import org.lightmtv.config.UrlConfigEntry;

/**
 * @author gl
 * @since Jul 1, 2008
 */
public class StandardUrlConfig {
	private static final Log log = LogFactory.getLog(StandardUrlConfig.class);
	private PatternMap<UrlConfigEntry> urlMap;
	private PatternMap<String> filterMap;
	public StandardUrlConfig(InputStream is) {
		urlMap = new PatternMap<UrlConfigEntry>();
		filterMap = new PatternMap<String>();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
			init(br);
		} catch (UnsupportedEncodingException e) {
		} catch (IOException e) {
			log.warn(e);
		}
	}

	/**
	 * @param br
	 * @throws IOException 
	 */
	private void init(BufferedReader br) throws IOException {
		//TODO: rewrite this,优化
		Pattern action=Pattern.compile("(.*)->(.*)");
		Pattern include=Pattern.compile("(.*)=>(.*)");
		Pattern redirect=Pattern.compile("(.*)-->(.*)");
		Pattern rewrite=Pattern.compile("(.*)==>(.*)");
		Pattern filter=Pattern.compile("(.*)>>(.*)");
		String line;
		while((line=br.readLine())!=null){
			line = line.trim();
			if(line.length()==0 || line.startsWith("#"))
				continue;
			boolean handled=handlePattern(action, line, UrlConfigEntry.ACTION)
				|| handlePattern(include, line, UrlConfigEntry.INCLUDE)
				|| handlePattern(redirect, line, UrlConfigEntry.REDIRECT)
				|| handlePattern(rewrite, line, UrlConfigEntry.REWRITE);

			if(!handled){
				Matcher matcher = filter.matcher(line);
				if(matcher.matches()){
					filterMap.put(Pattern.compile(matcher.group(1).trim()), matcher.group(2).trim());
				}else{
					throw new LightMtvException("error in 'url.conf' of line:'"+line+"'");
				}
			}
		}
	}

	private boolean handlePattern(Pattern pattern,String line,int type){
		Matcher matcher = pattern.matcher(line);
		if(matcher.matches()){
			UrlConfigEntry e = new UrlConfigEntry();
			e.setType(type);
			e.setPath(matcher.group(2).trim());
			urlMap.put(Pattern.compile(matcher.group(1).trim()), e);
		}
		return matcher.matches();
	}
	
	/**
	 * 
	 */
	public PatternMap<UrlConfigEntry> getUrlPatternMap() {
		return urlMap;
	}

	public PatternMap<String> getFilterPatternMap() {
		return filterMap;
	}
	
}
